package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.DeviceInfo;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.BedVo;
import com.zzyl.nursing.vo.RoomVo;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Slf4j
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    @Override
    public RoomVo one(Long id) {
        return roomMapper.one(id);
    }

    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
        List<RoomVo> roomVos = roomMapper.selectByFloorIdWithDevice(floorId);
        //上面通过数据库获得的都没有数据，下面通过redis获取
        //获取房间的设备
        if (CollectionUtil.isNotEmpty(roomVos)){
            //可能是多个设备
            for (RoomVo roomVo : roomVos) {
                List<DeviceInfo> deviceVos = roomVo.getDeviceVos();
                if (CollectionUtil.isNotEmpty(deviceVos)){
                    //获取每个设备的数据
                    extracted(deviceVos);
                }
                //获取床的设备
                List<BedVo> bedVoList = roomVo.getBedVoList();
                if (CollectionUtil.isNotEmpty(bedVoList)){
                    for (BedVo bedVo : bedVoList) {
                        //获取床的设备
                        List<DeviceInfo> bedDeviceVos = bedVo.getDeviceVos();
                        if(CollectionUtil.isNotEmpty(bedDeviceVos)){
                            extracted(bedDeviceVos);
                        }
                    }
                }
            }
        }



        //可能是多个设备
        return roomVos;
    }

    private void extracted(List<DeviceInfo> deviceVos) {
        for (DeviceInfo deviceVo : deviceVos) {
            String iotId = deviceVo.getIotId();
            String o = (String) (stringRedisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId));
            if (StringUtils.hasText(o)) {
                log.info("原始JSON字符串: {}", o);
                // 打印 o 的值用于调试
                try {
                    List<DeviceData> list = JSONUtil.toList(o, DeviceData.class);
                    deviceVo.setDeviceDataVos(list);
                } catch (Exception e) {
                    log.error("解析设备数据失败，JSON格式错误: {}", o, e);
                }
            }

        }
    }
}
